package com.futvan.z.framework.core;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.QueryTerms;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.util.DateUtil;
import com.futvan.z.framework.util.JsonUtil;
import com.futvan.z.framework.util.MathUtil;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.system.zdb.z_db_table;
import com.futvan.z.system.zdb.z_db_table_column;
import com.futvan.z.system.zform.z_form;
import com.futvan.z.system.zform.z_form_table;
import com.futvan.z.system.zform.z_form_table_column;
import com.futvan.z.system.zformquery.z_form_query;
import com.futvan.z.system.zorg.z_org;
import com.futvan.z.system.zregex.z_regex;
import com.futvan.z.system.zreport.z_report;
import com.futvan.z.system.zreport.z_report_button;
import com.futvan.z.system.zreport.z_report_column;
import com.futvan.z.system.zreportquery.z_report_query;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

@Transactional(rollbackFor = {Exception.class})
public class SuperService extends SuperZ{

	protected <T> T selectBean(String sql, Class<T> cla) {
		T bean = null;
		try {
			HashMap map = sqlSession.selectOne("select", sql);
			if(z.isNotNull(map) && map.size()>0) {
				bean = cla.newInstance();
				BeanUtils.populate(bean, map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;

	}

	protected <T> T selectBean(SqlSession ss,String sqlid,String sql) {
		return ss.selectOne(sqlid, sql);
	}

	protected <T> T selectBean(String sqlid, Object parameter) {
		return sqlSession.selectOne(sqlid, parameter);
	}

	protected <T> T selectBean(SqlSession ss, String sql, Class<T> cla) {
		T bean = null;
		try {
			HashMap map = ss.selectOne("select", sql);
			if(z.isNotNull(map) && map.size()>0) {
				bean = cla.newInstance();
				BeanUtils.populate(bean, map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;
	}

	protected HashMap<String,String> selectMap(String sql){
		return sqlSession.selectOne("select", sql);
	}

	protected HashMap<String,String> selectMap(SqlSession ss,String sql){
		return ss.selectOne("select", sql);
	}



	/**
	 * 根据Bean查询表数据
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	protected HashMap<String,String> selectMap(HashMap<String,String> bean) throws Exception {

		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}

		//生成sql
		String sql = CreateSelectSQL(bean,table,columnMap,columnList);

		//执行SQL
		List<HashMap> list = null;
		if(z.isNotNull(table.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(table.getDbid());
			list = s.selectList("select", sql);
		}else {
			z.Exception("selectMap: dbid is null");
		}
		if(list.size()==1) {
			bean.putAll(list.get(0));
			return bean;
		}else {
			throw new Exception("selectOne查询结果异常，返回"+list.size()+"条数据");
		}
	}


	protected <E> List<E> selectList(String sql){
		return sqlSession.selectList("select", sql);
	}
	protected <T> List<T> selectList(String sql, Class<T> cla){
		List<T> list = new ArrayList<T>();
		try {
			List<HashMap<String,String>> list_map = sqlSession.selectList("select", sql);
			for (HashMap<String, String> map : list_map) {
				if(z.isNotNull(map) && map.size()>0) {
					T bean = cla.newInstance();
					BeanUtils.populate(bean, map);
					list.add(bean);
				}
			}
		} catch (Exception e) {
			z.Error("selectList 执行出错|SQL:"+sql+"|Class<T>:"+cla.getSimpleName(), e);
		}
		return list;
	}
	protected <E> List<E> selectList(SqlSession ss,String sql){
		return ss.selectList("select", sql);
	}
	protected <E> List<E> selectList(String sqlid, Object parameter){
		return sqlSession.selectList(sqlid, parameter);
	}
	protected <E> List<E> selectList(SqlSession ss,String sqlid, Object parameter){
		return ss.selectList(sqlid, parameter);
	}
	protected <E> List<E> selectList(SqlSession ss,String sqlid,String sql){
		return ss.selectList(sqlid, sql);
	}



	/**
	 * 根据Bean查询表数据
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	protected List<HashMap<String,String>> selectList(HashMap<String,String> bean) throws Exception {

		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}

		//生成sql
		String sql = CreateSelectSQL(bean,table,columnMap,columnList);

		//执行SQL
		List<HashMap<String,String>> list = null;
		if(z.isNotNull(table.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(table.getDbid());
			list = s.selectList("select", sql);
		}else {
			z.Exception("selectList: dbid is null");
		}

		//设置计算返回记录总数,总页数
		selectCount(bean);
		return list;
	}


	/**
	 * 根据Bean查询表数据
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	protected List<HashMap<String,Object>> selectListAll(HashMap<String,String> bean) throws Exception {

		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}

		//生成sql
		String sql = CreateSelectSQL(bean,table,columnMap,columnList);

		//执行SQL
		List<HashMap<String,Object>> list = sqlSession.selectList("select", sql);
		//获取子表信息
		for (int i = 0; i < list.size(); i++) {
			List<z_form_table> dtableList = table.getZ_form_table_detail_list();
			for (z_form_table dtable : dtableList) {
				GetDetailList(list.get(i),dtable.getTable_id());
			}
		}

		//设置计算返回记录总数,总页数
		selectCount(bean);
		return list;
	}

	/**
	 * 根据主表数据zid和表名，获取子表关联数据
	 * @param c
	 * @param tableId
	 * @throws Exception
	 */
	private void GetDetailList(HashMap<String, Object> c, String tableId) throws Exception {
		HashMap<String,String> bean = new HashMap<String, String>();
		bean.put("pid", String.valueOf(c.get("zid")));
		bean.put("tableId", tableId);
		//根据主表zid获取当前表数据
		List<HashMap<String,String>> list = selectList(bean);
		c.put(tableId+"_list", list);
		//判读是否有下级表
		List<z_form_table> dtableList = z.tables.get(tableId).getZ_form_table_detail_list();
		for (z_form_table dtable : dtableList) {
			GetDetailList(c,dtable.getTable_id());
		}
	}


	protected List<String> selectListString(String sql){
		return sqlSession.selectList("selectone", sql);
	}


	/**
	 * 根据Bean查询总记录数
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	protected int selectCount(HashMap<String,String> bean) throws Exception {
		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}

		//创建执行SQL
		String sql = CreateSelectCountSQL(bean,table,columnMap,columnList);

		//设置返回记录总数
		int datacount = 0;
		if(z.isNotNull(table.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(table.getDbid());
			datacount = s.selectOne("selectoneint", sql);
		}else {
			z.Exception("selectCount: dbid is null");
		}

		bean.put("datacount", String.valueOf(datacount));

		//设置总页数
		int rowcount = new Integer(z.sp.get("rowcount"));
		if(z.isNotNull(bean.get("rowcount"))) {
			rowcount = new Integer(bean.get("rowcount"));
		}
		bean.put("pagecount", MathUtil.getPageCount(datacount,rowcount));
		return datacount;
	}


	/**
	 * 根据主表bean查询所有明细表记录
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	protected Map<String, List<HashMap>> selectDetailsMap(HashMap<String, String> bean) throws Exception {
		Map<String, List<HashMap>> result = new HashMap<String, List<HashMap>>();

		//获取主表表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		//获取明细表名
		List<z_form_table> detailTableName = table.getZ_form_table_detail_list();
		if(detailTableName!=null && detailTableName.size()>0) {
			for (z_form_table dTable : detailTableName) {
				//生成sql
				String sql = CreateSelectDetailSQL(bean,dTable);

				//执行SQL
				List<HashMap> list = null;
				if(z.isNotNull(table.getDbid())) {
					SqlSessionTemplate s = z.dbs.get(table.getDbid());
					list = s.selectList("select", sql);
				}else {
					z.Exception("selectDetailsMap: dbid is null");
				}
				result.put(dTable.getTable_id(), list);
			}
		}

		return result;
	}


	protected int selectInt(String sql){
		return sqlSession.selectOne("selectoneint", sql);
	}

	protected int selectInt(SqlSession ss,String sql){
		return ss.selectOne("selectoneint", sql);
	}

	protected BigDecimal selectBigDecimal(String sql){
		return sqlSession.selectOne("selectonebigdecimal", sql);
	}

	protected BigDecimal selectBigDecimal(SqlSession ss,String sql){
		return ss.selectOne("selectonebigdecimal", sql);
	}


	protected String selectString(String sql){
		return sqlSession.selectOne("selectone", sql);
	}
	protected String selectString(SqlSession ss,String sql){
		return ss.selectOne("selectone", sql);
	}

	protected int insert(String sql) throws RuntimeException{
		String []sqlarray = sql.split("☆");
		int rnum = 0;
		for (String s : sqlarray) {
			if(z.isNotNull(s) && z.isNotNull(s.trim())) {
				int tempnum = sqlSession.insert("insert", s);
				rnum = rnum + tempnum;
			}
		}
		return rnum;
	}

	protected int insert(SqlSession ss,String sql){
		return ss.insert("insert", sql);
	}

	protected int insert(String sqlid, Object parameter) throws RuntimeException{
		return sqlSession.insert(sqlid, parameter);
	}

	protected Result insert(HashMap<String,String> bean) throws Exception {
		return insert(bean,null);
	}


	protected Result insert(HashMap<String,String> bean,HttpServletRequest request) throws Exception {
		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}
		//插入前事件
		insertBefore(bean,table,columnMap,columnList);

		Result result = new Result();

		//生成zid 如果number不为空，默认zid=number
		if(z.isNotNull(bean.get("number"))){
			bean.put("zid",bean.get("number"));
		}else{
			if(z.isNull(bean.get("zid"))){
				bean.put("zid", z.newZid(table.getTable_id()));
			}
		}

		//创建执行SQL
		String sql = CreateInsertSQL(bean,table,columnMap,columnList);
		int count = 0;
		if(z.isNotNull(table.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(table.getDbid());
			count = s.insert("insert",sql);
		}else {
			z.Exception("insert: dbid is null");
		}

		if(count!=1) {
			result.setCode(Code.ERROR);
			result.setMsg("insert异常，同时插入"+count+"条数据");
		}else {
			//执行插入后事件
			insertAfter(bean,table,columnMap,columnList);

			//设置返回
			result.setCode(Code.SUCCESS);
			result.setMsg("保存成功");
			result.setData(BeanUtils.getProperty(bean, "zid"));

		}
		return result;
	}

	/**
	 * 新增方法，不执行事件
	 * @param bean
	 * @param request
	 * @return
	 * @throws Exception
	 */
	protected Result insertNotEvent(HashMap<String,String> bean,HttpServletRequest request) throws Exception {
		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}
		Result result = new Result();

		//生成zid 如果number不为空，默认zid=number
		if(z.isNotNull(bean.get("number"))){
			bean.put("zid",bean.get("number"));
		}else{
			if(z.isNull(bean.get("zid"))){
				bean.put("zid", z.newZid(table.getTable_id()));
			}
		}

		//创建执行SQL
		String sql = CreateInsertSQL(bean,table,columnMap,columnList);
		int count = 0;
		if(z.isNotNull(table.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(table.getDbid());
			count = s.insert("insert",sql);
		}else {
			z.Exception("insert: dbid is null");
		}

		if(count!=1) {
			result.setCode(Code.ERROR);
			result.setMsg("insert异常，同时插入"+count+"条数据");
		}else {
			//设置返回
			result.setCode(Code.SUCCESS);
			result.setMsg("保存成功");
			result.setData(BeanUtils.getProperty(bean, "zid"));

		}
		return result;
	}

	protected Result insertOtherDB(SqlSession ss,HashMap<String,String> bean) throws Exception {
		Result result = new Result();
		String dbid = bean.get("dbid");
		String table_name = bean.get("tableId");
		z_db_table table = z.dbTableMap.get(dbid+"_"+table_name);
		if(table==null) {
			result.setCode(Code.ERROR);
			result.setMsg(dbid+"库中，未找到"+table_name+"表");
		}else {
			//获取数据库连接
			if(z.isNotNull(ss)) {
				//创建执行SQL
				String sql = CreateOtherDBInsertSQL(table,bean);
				int count = ss.insert("insert",sql);
				if(count!=1) {
					result.setCode(Code.ERROR);
					result.setMsg("insert异常，同时插入"+count+"条数据");
				}else {
					//设置返回
					result.setCode(Code.SUCCESS);
					result.setMsg("保存成功");
					result.setData(bean);
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("未获取到数据库"+dbid+"的链接");
			}
		}
		return result;
	}

	protected int update(String sql){
		String []sqlarray = sql.split("☆");
		int rnum = 0;
		for (String s : sqlarray) {
			if(z.isNotNull(s) && z.isNotNull(s.trim())) {
				int tempnum = sqlSession.update("update", s);
				rnum = rnum + tempnum;
			}
		}
		return rnum;
	}

	protected int update(SqlSession ss,String sql){
		return ss.insert("update", sql);
	}

	protected int update(String sqlid,Object parameter){
		return sqlSession.update(sqlid, parameter);
	}


	protected Result update(HashMap<String,String> bean) throws Exception{
		return update(bean,null);
	}

	protected Result update(HashMap<String,String> bean,HttpServletRequest request) throws Exception{
		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}
		//修改前事件
		updateBefore(bean,table,columnMap,columnList);

		Result result = new Result();
		//创建执行SQL
		String sql = CreateUpdateSQL(bean,table,columnMap,columnList);
		int count = 0;
		if(z.isNotNull(table.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(table.getDbid());
			count = s.update("update",sql);
		}else {
			z.Exception("selectList: dbid is null");
		}
		if(count==0) {
			result.setCode(Code.ERROR);
			result.setMsg("保存数据失败，该记录经已被修改，请刷新后重新修改保存。");
		}else {
			//更新后事件
			updateAfter(bean,table,columnMap,columnList);

			result.setCode(Code.SUCCESS);
			result.setMsg("保存成功");
			result.setData(BeanUtils.getProperty(bean, "zid"));
		}
		return result;
	}

	protected Result updateForBean(HashMap<String,String> bean,HttpServletRequest request) throws Exception{
		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}
		//修改前事件
		updateBefore(bean,table,columnMap,columnList);

		Result result = new Result();
		//创建执行SQL
		String sql = CreateUpdateForBeanSQL(bean,table,columnMap,columnList);
		int count = sqlSession.update("update",sql);
		if(count==0) {
			result.setCode(Code.ERROR);
			result.setMsg("保存数据失败，该记录经已被修改，请刷新后重新保存。");
		}else {
			//更新后事件
			updateAfter(bean,table,columnMap,columnList);

			result.setCode(Code.SUCCESS);
			result.setMsg("保存成功");
			result.setData(BeanUtils.getProperty(bean, "zid"));
		}
		return result;
	}

	/**
	 * 修改方法-不执行事件
	 * @param bean
	 * @param request
	 * @return
	 * @throws Exception
	 */
	protected Result updateNotEvent(HashMap<String, String> bean, HttpServletRequest request) throws Exception {
		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}

		Result result = new Result();
		//创建执行SQL
		String sql = CreateUpdateSQL(bean,table,columnMap,columnList);
		int count = 0;
		if(z.isNotNull(table.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(table.getDbid());
			count = s.update("update",sql);
		}else {
			z.Exception("selectList: dbid is null");
		}
		if(count==0) {
			result.setCode(Code.ERROR);
			result.setMsg("保存数据失败，该记录经已被修改，请刷新后重新保存。");
		}else {
			result.setCode(Code.SUCCESS);
			result.setMsg("保存成功");
			result.setData(BeanUtils.getProperty(bean, "zid"));
		}
		return result;
	}

	protected int delete(String sql){
		String []sqlarray = sql.split("☆");
		int rnum = 0;
		for (String s : sqlarray) {
			if(z.isNotNull(s) && z.isNotNull(s.trim())) {
				int tempnum = sqlSession.delete("delete", s);
				rnum = rnum + tempnum;
			}
		}
		return rnum;
	}

	protected int delete(SqlSession ss,String sql){
		String []sqlarray = sql.split("☆");
		int rnum = 0;
		for (String s : sqlarray) {
			if(z.isNotNull(s) && z.isNotNull(s.trim())) {
				int tempnum = ss.delete("delete", s);
				rnum = rnum + tempnum;
			}
		}
		return rnum;
	}



	protected int delete(String sqlid,Object parameter){
		return sqlSession.delete(sqlid, parameter);
	}

	/**
	 * 根据Bean查询表数据
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	protected Result delete(HashMap<String,String> bean) throws Exception {
		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(table==null) {
			throw new Exception("tableId无效");
		}
		List<z_form_table_column> columnList = table.getZ_form_table_column_list();
		//根据List转成Map
		HashMap<String,z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_form_table_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}

		//删除前事件
		deleteBefore(bean, table, columnMap, columnList);

		//执行删除任务
		Result result = new Result();
		String zids = bean.get("zids");
		String TableName = bean.get("tableId");
		SqlSessionTemplate s = null;
		if(z.isNotNull(table.getDbid())) {
			s = z.dbs.get(table.getDbid());
		}else {
			z.Exception("delete: dbid is null");
		}
		int romcount = 0;
		if(!"".equals(TableName) && TableName!=null) {
			if(!"".equals(zids) && zids!=null) {
				String [] zids_array = zids.split(",");

				for (int i = 0; i < zids_array.length; i++) {

					//主表主键
					String zid = zids_array[i];


					//删除明细表
					deleteDetailTable(s,TableName,zid);

					//删除主表
					String sql = "delete from "+TableName + " where zid = '"+zid+"'";
					int deletecounts = s.delete("delete", sql);
					//如果删除成功，累计删除条数
					if(deletecounts>0) {
						romcount = romcount + deletecounts;
					}
				}
				if(romcount>0) {
					deleteAfter(bean, table, columnMap, columnList);
					result.setCode(Code.SUCCESS);
					result.setMsg("ok");
					result.setData(romcount);
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("删除0条记录");
				}
			}else {
				StringBuffer sql = new StringBuffer();
				sql.append("delete from "+TableName+" where 1=1 ");
				int where_num = 0;//where条件的数据

				//添加条件
				for (String key : bean.keySet()) {
					String name = key;//获取参数名
					if(columnMap.get(key)!=null || columnMap.get(key.replace("_from", ""))!=null) {
						if(columnMap.get(key.replace("_from", ""))!=null) {
							name = key.replace("_from", "");
						}
						if(!"pagenum".equals(name)
								&& !"rowcount".equals(name)
								&& !"pagecount".equals(name)
								&& !"datacount".equals(name)
								&& !"query_terms".equals(name)
								&& !"otherwhere".equals(name)
								&& !"orderby".equals(name)
								&& !"orderby_pattern".equals(name)
								&& !"tableId".equals(name)
								&& !"list_dblclick".equals(name)
								&& !"info".equals(name)
								&& !"info_map".equals(name)){

							//获取字段链接符号
							String compare = columnMap.get(name).getCompare();

							String value = bean.get(name);//根据参数名获取值
							where_num = where_num+1;
							if(z.isNull(compare) && z.isNotNull(value)) {
								sql.append(" and "+name+" = "+"'"+value+"'");
							}else {
								//拼接Where条件
								if("0".equals(compare) && z.isNotNull(value)) {
									sql.append(" and "+name+" = "+"'"+value+"'");
								}else if("1".equals(compare) && z.isNotNull(value)) {
									sql.append(" and "+name+" like "+"'%"+value+"%'");
								}else if("2".equals(compare) && z.isNotNull(value)) {
									sql.append(" and "+name+" in("+StringUtil.ListToSqlInArray(value)+")");
								}else if("3".equals(compare) && z.isNotNull(bean.get(name+"_from")) && z.isNotNull(bean.get(name+"_to"))) {
									String from_value = bean.get(name+"_from");//获取区间开始值
									String to_value = bean.get(name+"_to");//获取区间结束值
									//如果字段类型为日期，增加日期格式化处理在比较
									if("9".equals(columnMap.get(name).getColumn_type())) {
										sql.append(" and (DATE_FORMAT("+name+",'%Y-%m-%d') >= '"+from_value+"'  and DATE_FORMAT("+name+",'%Y-%m-%d') <= '"+to_value+"' ) ");
									}else {
										sql.append(" and ("+name+" >= '"+from_value+"'  and "+name+" <= '"+to_value+"' ) ");
									}
								}
							}


						}

					}
				}

				if(where_num>0){
					int deletecounts = s.delete("delete", sql);
					//如果删除成功，累计删除条数
					if(deletecounts>0) {
						romcount = romcount + deletecounts;
					}
					if(romcount>0) {
						deleteAfter(bean, table, columnMap, columnList);
						result.setCode(Code.SUCCESS);
						result.setMsg("ok");
						result.setData(romcount);
					}else {
						result.setCode(Code.ERROR);
						result.setMsg("删除0条记录");
					}
				}else{
					result.setCode(Code.ERROR);
					result.setMsg("执行删除出错：删除条件不可为空");
				}
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("table name is null");
		}
		return result;
	}

	/**
	 * 删除明细表数据
	 * @param s
	 * @param TableName 表名
	 * @param czid 主表主键
	 */
	private void deleteDetailTable(SqlSessionTemplate s, String TableName,String czid) {
		//获取子表
		List<HashMap> dtableMap = sqlSession.selectList("select", "SELECT c.table_id ,(SELECT COUNT(*) FROM z_form_table d WHERE d.parent_table_id = c.table_id) dtnum FROM z_form_table c WHERE c.parent_table_id =  '"+TableName+"'");
		for (HashMap dtable : dtableMap) {
			BigDecimal dtnum_int = new BigDecimal(String.valueOf(dtable.get("dtnum")));
			String dtableid = String.valueOf(dtable.get("table_id"));
			if(dtnum_int.intValue()>0) {
				List<String> dzidlist = s.selectList("selectone", "SELECT zid FROM "+dtableid+" WHERE pid = '"+czid+"'");
				for (String dzid : dzidlist) {
					deleteDetailTable(s,dtableid,dzid);
				}
			}
			s.delete("delete", "delete from "+dtableid + " where pid = '"+czid+"'");
		}
	}

	/**
	 * 	手动提交事务
	 */
	protected void commit() {
		sqlSession.commit();
	}


	private void insertBefore(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception {
		for(z_form_table_column column:columnList) {
			String name = column.getColumn_id();//获取参数名
			String value = bean.get(column.getColumn_id());
			if(!"zid".equals(name)
					&& !"create_user".equals(name)
					&& !"update_user".equals(name)
					&& !"create_time".equals(name)
					&& !"update_time".equals(name)
					&& !"seq".equals(name)
					&& !"orgid".equals(name)
					&& !"zversion".equals(name)
					&& column!=null){
				if(z.isNotNull(value)) {
					//字段必须是表定义中包含的字段
					if(z.isNotNull(columnMap.get(name))) {
						//验证是否唯一
						if("1".equals(column.getIs_only())){
							int n = selectInt("select count(*) n from "+table.getTable_id()+" where "+name+"='"+value+"'");
							if(n>0){
								z.Exception("insert异常|["+column.getColumn_name()+"]值重复,违反唯一性要求，无法保存");
							}
						}

						//验证有正则表达式的字段
						if(z.isNotNull(column.getRegex())){
							z_regex r = z.regexs.get(column.getRegex());
							if(z.isNotNull(r) && z.isNotNull(r.getRegex())){
								boolean v = StringUtil.vRegex(value,r.getRegex());
								if(!v){
									z.Exception("insert异常|["+column.getColumn_name()+"]数据值校验失败，不符合["+r.getName()+"]验证规则");
								}
							}
						}


					}
				}
			}
		}

	}



	private void insertAfter(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception {
	}

	private void updateBefore(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception {
		for(z_form_table_column column:columnList) {
			String name = column.getColumn_id();//获取参数名
			String value = bean.get(column.getColumn_id());
			if(!"zid".equals(name)
					&& !"create_user".equals(name)
					&& !"update_user".equals(name)
					&& !"create_time".equals(name)
					&& !"update_time".equals(name)
					&& !"seq".equals(name)
					&& !"orgid".equals(name)
					&& !"zversion".equals(name)
					&& column!=null){
				if(z.isNotNull(value)) {
					//字段必须是表定义中包含的字段
					if(z.isNotNull(columnMap.get(name))) {
						//验证是否唯一
						if("1".equals(column.getIs_only())){
							String zid = bean.get("zid");
							int n = selectInt("select count(*) n from "+table.getTable_id()+" where "+name+"='"+value+"' and zid != '"+zid+"'");
							if(n>0){
								z.Exception("保存数据失败，【"+column.getColumn_name()+"】值重复,违反唯一性要求，无法保存");
							}
						}

						//验证有正则表达式的字段
						if(z.isNotNull(column.getRegex())){
							z_regex r = z.regexs.get(column.getRegex());
							if(z.isNotNull(r) && z.isNotNull(r.getRegex())){
								boolean v = StringUtil.vRegex(value,r.getRegex());
								if(!v){
									z.Exception("保存数据失败，【"+column.getColumn_name()+"】数据值校验失败，不符合【"+r.getName()+"】验证规则");
								}
							}
						}


					}
				}
			}
		}
	}

	private void updateAfter(HashMap<String, String> bean, z_form_table table,HashMap<String, z_form_table_column> columnMap, List<z_form_table_column> columnList) {
	}

	private void deleteBefore(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception {
	}

	private void deleteAfter(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception {
	}

	/**
	 * 生成SQL
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	private String CreateSelectSQL(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception{
		if(table!=null && columnList!=null && columnList.size()>0) {
			//创建SQL
			StringBuffer sql = new StringBuffer();
			sql.append("select ");

			//添加字段
			for (int i = 0; i < columnList.size(); i++) {
				z_form_table_column column = columnList.get(i);
				if(i==columnList.size()-1) {
					if("9".equals(column.getColumn_type())){
						sql.append("DATE_FORMAT("+column.getColumn_id()+",'%Y-%m-%d') "+column.getColumn_id());
					}else if("10".equals(column.getColumn_type())){
						sql.append("DATE_FORMAT("+column.getColumn_id()+",'%Y-%m-%d %H:%i:%s') "+column.getColumn_id());
					}else{
						sql.append(column.getColumn_id());
					}
				}else {
					if("9".equals(column.getColumn_type())){
						sql.append("DATE_FORMAT("+column.getColumn_id()+",'%Y-%m-%d') "+column.getColumn_id()+",");
					}else if("10".equals(column.getColumn_type())){
						sql.append("DATE_FORMAT("+column.getColumn_id()+",'%Y-%m-%d %H:%i:%s') "+column.getColumn_id()+",");
					}else{
						sql.append(column.getColumn_id()+",");
					}
				}
			}

			sql.append(" from "+table.getTable_id());
			sql.append(" where 1=1 ");

			//添加条件
			for (String key : bean.keySet()) {
				String name = key;//获取参数名
				if(columnMap.get(key)!=null || columnMap.get(key.replace("_from", ""))!=null) {

					if(columnMap.get(key.replace("_from", ""))!=null) {
						name = key.replace("_from", "");
					}

					if(!"pagenum".equals(name)
							&& !"rowcount".equals(name)
							&& !"pagecount".equals(name)
							&& !"datacount".equals(name)
							&& !"query_terms".equals(name)
							&& !"otherwhere".equals(name)
							&& !"orderby".equals(name)
							&& !"orderby_pattern".equals(name)
							&& !"tableId".equals(name)
							&& !"list_dblclick".equals(name)
							&& !"info".equals(name)
							&& !"info_map".equals(name)){

						//获取字段链接符号
						String compare = columnMap.get(name).getCompare();

						String value = bean.get(name);//根据参数名获取值
						if(z.isNull(compare) && z.isNotNull(value)) {
							sql.append(" and "+name+" = "+"'"+value+"'");
						}else {
							//拼接Where条件
							if("0".equals(compare) && z.isNotNull(value)) {
								sql.append(" and "+name+" = "+"'"+value+"'");
							}else if("1".equals(compare) && z.isNotNull(value)) {
								sql.append(" and "+name+" like "+"'%"+value+"%'");
							}else if("2".equals(compare) && z.isNotNull(value)) {
								sql.append(" and "+name+" in("+StringUtil.ListToSqlInArray(value)+")");
							}else if("3".equals(compare) && z.isNotNull(bean.get(name+"_from")) && z.isNotNull(bean.get(name+"_to"))) {
								String from_value = bean.get(name+"_from");//获取区间开始值
								String to_value = bean.get(name+"_to");//获取区间结束值
								//如果字段类型为日期，增加日期格式化处理在比较
								if("9".equals(columnMap.get(name).getColumn_type())) {
									sql.append(" and (DATE_FORMAT("+name+",'%Y-%m-%d') >= '"+from_value+"'  and DATE_FORMAT("+name+",'%Y-%m-%d') <= '"+to_value+"' ) ");
								}else if("10".equals(columnMap.get(name).getColumn_type())) {
									sql.append(" and (DATE_FORMAT("+name+",'%Y-%m-%d %H:%i:%s') >= '"+from_value+"'  and DATE_FORMAT("+name+",'%Y-%m-%d %H:%i:%s') <= '"+to_value+"' ) ");
								}else{
									sql.append(" and ("+name+" >= '"+from_value+"'  and "+name+" <= '"+to_value+"' ) ");
								}
							}
						}


					}

				}


			}

			//添加综合查询条件
			if(!"".equals(bean.get("query_terms")) && bean.get("query_terms")!=null) {
				String query_terms_sql = CreateQueryTerms(bean.get("query_terms"));
				if(!"".equals(query_terms_sql) && query_terms_sql!=null) {
					sql.append(" and "+query_terms_sql+" ");
				}
			}

			//添加其它条件
			if(!"".equals(bean.get("otherwhere")) && bean.get("otherwhere")!=null) {
				sql.append(" and "+bean.get("otherwhere")+" ");
			}

			//添加数据隔离模式条件  isolation_mode == 0 代表全员可见
			z_form form = z.form_tableid.get(table.getTable_id());
			if(z.isNotNull(form) && z.isNotNull(form.getIsolation_mode()) && !"0".equals(form.getIsolation_mode()) && !"sa".equals(bean.get("session_userid"))) {
				String session_userid = bean.get("session_userid");//当前登录用户
				String session_orgid = bean.get("session_orgid");//当前登录组织

				if("1".equals(form.getIsolation_mode()) && z.isNotNull(session_userid)){
					//本人可见
					sql.append(" and create_user = "+"'"+session_userid+"'");
				}else if("2".equals(form.getIsolation_mode()) && z.isNotNull(session_orgid)) {
					//同组织用户可见
					sql.append(" and orgid = "+"'"+session_orgid+"'");
				}else if("3".equals(form.getIsolation_mode()) && z.isNotNull(session_userid) && z.isNotNull(session_orgid)) {
					//直属领导可见
					//获取当前登录人所负责组织下的所有用户用户，注意，登录人负责的组织必须是当前登录的组织
					StringBuffer OrgUserListSQL = new StringBuffer();
					OrgUserListSQL.append(" SELECT cu.userid ");
					OrgUserListSQL.append(" FROM z_org c  ");
					OrgUserListSQL.append(" INNER JOIN z_org_user cu ON c.zid = cu.pid ");
					OrgUserListSQL.append(" WHERE c.zid = '"+session_orgid+"' ");//登录组织必须是登录人负责的组织
					OrgUserListSQL.append(" AND c.user_head = '"+session_userid+"' ");//负责人必须是登录人自己
					List<String> userlist = sqlSession.selectList("selectone", OrgUserListSQL);
					if(z.isNotNull(userlist) && userlist.size()>0) {
						//判读是否包含当前登录人自己，如果包含，添加当前登录人到列表中
						if(!userlist.contains(session_userid)) {
							userlist.add(session_userid);
						}
						String userListInString = StringUtil.ListToString(userlist, ",", "'", "'");
						sql.append(" and create_user in("+userListInString+") ");
					}else {
						//本人查看
						sql.append(" and create_user = "+"'"+session_userid+"'");
					}
				}else if("4".equals(form.getIsolation_mode())) {
					//上级领导可见
					z_org noworg = z.orgs.get(session_orgid);
					if(z.isNotNull(noworg)) {
						//获取所有下级组织用户列表
						List<String> userList = z.lowerOrgUsers.get(session_orgid);
						if(z.isNull(userList)) {
							userList = new ArrayList<String>();
						}
						//添加自己
						userList.add(session_userid);
						String userListString = StringUtil.ListToString(userList, ",", "'", "'");
						sql.append(" and create_user in("+userListString+") ");
					}else {
						//本人查看
						sql.append(" and create_user = "+"'"+session_userid+"'");
					}
				}
			}



			//添加 Z5页面通用查询框使用
			if(!"".equals(bean.get("Z5QueryParameters")) && bean.get("Z5QueryParameters")!=null && !"null".equals(bean.get("Z5QueryParameters"))) {
				sql.append(" and ( ");
				for (int i = 0; i < columnList.size(); i++) {
					z_form_table_column column = columnList.get(i);

					if("1".equals(column.getIs_z5_display())){
						String like = " like ";
						//若字段类型 Type 是 time,date,datetime  必需改成 like binary '%中文%' 即可避免出现错误.
						if("9".equals(column.getColumn_type()) || "10".equals(column.getColumn_type())) {
							like = " like binary ";
						}
						if(i==0) {
							sql.append(column.getColumn_id()+like+"'%"+bean.get("Z5QueryParameters")+"%'");
						}else {
							sql.append(" or "+column.getColumn_id()+like+"'%"+bean.get("Z5QueryParameters")+"%'");
						}
					}
				}
				sql.append(" ) ");
			}

			//添加排序
			if(z.isNotNull(bean.get("orderby")) && z.isNotNull(bean.get("orderby_pattern"))) {
				//如果参数对象的orderby条件不为空，使用参数对象的条件
				sql.append(" order by "+bean.get("orderby")+" "+bean.get("orderby_pattern"));
			}else if(!"".equals(table.getOrderby()) && table.getOrderby()!=null) {
				//如果表定义的默认排序条件不为空，使用表的默认排序
				sql.append(" order by "+table.getOrderby()+" "+table.getOrderby_pattern());
			}

			//添加分页
			if(z.isNotNull(bean.get("pagenum")) && z.isNotNull(bean.get("rowcount"))) {

				int pagenum = Integer.valueOf(bean.get("pagenum"));//页号
				int rowcount = Integer.valueOf(bean.get("rowcount"));//分页显示行数
				if(pagenum>0 && rowcount>0) {//页号和分布显示行数都必须大于0
					int row_num = (pagenum-1)*rowcount;//分页开始行号
					sql.append(" limit "+row_num+","+bean.get("rowcount"));
				}else {
					sql.append(" limit 0,"+z.sp.get("rowcount"));
					bean.put("pagenum", "1");
					bean.put("rowcount", z.sp.get("rowcount"));
				}
			}
			//打印SQL
			return sql.toString();
		}else {
			return null;
		}
	}


	/**
	 * 生成SQL
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	private String CreateSelectCountSQL(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception{
		if(table!=null && columnList!=null && columnList.size()>0) {
			//创建SQL
			StringBuffer sql = new StringBuffer();
			sql.append("select count(*)");
			sql.append(" from "+table.getTable_id());
			sql.append(" where 1=1 ");

			//添加条件
			for (String key : bean.keySet()) {
				String name = key;//获取参数名
				if(columnMap.get(key)!=null || columnMap.get(key.replace("_from", ""))!=null) {

					if(columnMap.get(key.replace("_from", ""))!=null) {
						name = key.replace("_from", "");
					}

					if(!"pagenum".equals(name)
							&& !"rowcount".equals(name)
							&& !"pagecount".equals(name)
							&& !"datacount".equals(name)
							&& !"query_terms".equals(name)
							&& !"otherwhere".equals(name)
							&& !"orderby".equals(name)
							&& !"orderby_pattern".equals(name)
							&& !"tableId".equals(name)
							&& !"list_dblclick".equals(name)
							&& !"info".equals(name)
							&& !"info_map".equals(name)){

						//获取字段链接符号
						String compare = columnMap.get(name).getCompare();

						String value = bean.get(name);//根据参数名获取值
						if(z.isNull(compare) && z.isNotNull(value)) {
							sql.append(" and "+name+" = "+"'"+value+"'");
						}else {
							//拼接Where条件
							if("0".equals(compare) && z.isNotNull(value)) {
								sql.append(" and "+name+" = "+"'"+value+"'");
							}else if("1".equals(compare) && z.isNotNull(value)) {
								sql.append(" and "+name+" like "+"'%"+value+"%'");
							}else if("2".equals(compare) && z.isNotNull(value)) {
								sql.append(" and "+name+" in("+StringUtil.ListToSqlInArray(value)+")");
							}else if("3".equals(compare) && z.isNotNull(bean.get(name+"_from")) && z.isNotNull(bean.get(name+"_to"))) {
								String from_value = bean.get(name+"_from");//获取区间开始值
								String to_value = bean.get(name+"_to");//获取区间结束值
								//如果字段类型为日期，增加日期格式化处理在比较
								if("9".equals(columnMap.get(name).getColumn_type())) {
									sql.append(" and (DATE_FORMAT("+name+",'%Y-%m-%d') >= '"+from_value+"'  and DATE_FORMAT("+name+",'%Y-%m-%d') <= '"+to_value+"' ) ");
								}else {
									sql.append(" and ("+name+" >= '"+from_value+"'  and "+name+" <= '"+to_value+"' ) ");
								}
							}
						}


					}

				}


			}

			//添加查询条件
			if(!"".equals(bean.get("query_terms")) && bean.get("query_terms")!=null) {
				String query_terms_sql = CreateQueryTerms(bean.get("query_terms"));
				if(!"".equals(query_terms_sql) && query_terms_sql!=null) {
					sql.append(" and "+query_terms_sql+" ");
				}
			}

			//添加其它条件
			if(!"".equals(bean.get("otherwhere")) && bean.get("otherwhere")!=null) {
				sql.append(" and "+bean.get("otherwhere")+" ");
			}

			//添加综合查询条件
			if(!"".equals(bean.get("Z5QueryParameters")) && bean.get("Z5QueryParameters")!=null && !"null".equals(bean.get("Z5QueryParameters"))) {
				sql.append(" and ( ");
				for (int i = 0; i < columnList.size(); i++) {
					z_form_table_column column = columnList.get(i);

					String like = " like ";
					//若字段类型 Type 是 time,date,datetime  必需改成 like binary '%中文%' 即可避免出现错误.
					if("9".equals(column.getColumn_type()) || "10".equals(column.getColumn_type())) {
						like = " like binary ";
					}

					if(i==0) {
						sql.append(column.getColumn_id()+like+"'%"+bean.get("Z5QueryParameters")+"%'");
					}else {
						sql.append(" or "+column.getColumn_id()+like+"'%"+bean.get("Z5QueryParameters")+"%'");
					}

				}
				sql.append(" ) ");
			}


			return sql.toString();
		}else {
			return null;
		}
	}


	private String CreateSelectDetailSQL(HashMap<String, String> bean,z_form_table detailTable) throws Exception {
		StringBuffer sql = new StringBuffer();
		if(detailTable!=null) {
			sql.append("select ");
			//添加字段
			List<z_form_table_column> columnList = detailTable.getZ_form_table_column_list();
			for (z_form_table_column column : columnList) {
				if(		!"seq".equals(column.getColumn_id()) &&
						!"pid".equals(column.getColumn_id()) &&
						!"zid".equals(column.getColumn_id()) ) {
					sql.append(column.getColumn_id()+",");
				}

			}
			sql.append(" seq,pid,zid ");
			sql.append(" from "+detailTable.getTable_id());
			sql.append(" where pid ='"+bean.get("zid")+"' ");

			//添加排序
			if(!"".equals(detailTable.getOrderby()) && detailTable.getOrderby()!=null) {
				//如果参数对象的orderby条件不为空，使用参数对象的条件
				if(!"".equals(detailTable.getOrderby_pattern()) && detailTable.getOrderby_pattern()!=null) {
					sql.append(" order by "+detailTable.getOrderby()+" "+detailTable.getOrderby_pattern());
				}else {
					sql.append(" order by "+detailTable.getOrderby()+" ");
				}

			}
			return sql.toString();
		}else {
			return null;
		}
	}

	private String CreateOtherDBInsertSQL(z_db_table table, HashMap<String,String> bean) {
		StringBuffer sql = new StringBuffer();
		if(z.isNotNull(bean) && bean.size()>0 && z.isNotNull(table)) {
			String columns = "";
			String values = "";
			//遍历参数
			for (Map.Entry<String,String> column_entry : bean.entrySet()) {
				String column_name = column_entry.getKey();//获取参数名
				Object value = column_entry.getValue();
				if(!"tableId".equals(column_name) && !"dbid".equals(column_name) && z.isNotNull(value)){
					columns = columns + column_name +",";

					z_db_table_column column = z.dbTableColumnMap.get(bean.get("dbid")+"_"+table.getTable_id()+"_"+column_name);
					if("INT".equals(column.getColumn_type()) ||
							"BIGINT".equals(column.getColumn_type()) ||
							"BIT".equals(column.getColumn_type()) ||
							"DECIMAL".equals(column.getColumn_type())) {
						values = values +value+",";
					}else {
						values = values + "'"+value+"',";
					}
				}
			}
			columns = columns.substring(0, columns.length() - 1);
			values = values.substring(0, values.length() - 1);

			//创建SQL
			sql.append("insert into "+table.getTable_id()+" ( ");
			sql.append(columns);
			sql.append("  ) values ( ");
			sql.append(values);
			sql.append(" )");
		}
		return sql.toString();
	}
	/**
	 * 创建插入SQL
	 * @param bean
	 * @return
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws Exception
	 */
	private String CreateInsertSQL(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception{

		if(table!=null && columnList!=null && columnList.size()>0) {
			//创建SQL
			StringBuffer sql = new StringBuffer();
			sql.append("insert into "+table.getTable_id()+" ( ");
			for(z_form_table_column column:columnList) {
				String name = column.getColumn_id();//获取参数名
				String value = bean.get(column.getColumn_id());
				if(!"zid".equals(name)
						&& !"create_user".equals(name)
						&& !"update_user".equals(name)
						&& !"create_time".equals(name)
						&& !"update_time".equals(name)
						&& !"seq".equals(name)
						&& !"orgid".equals(name)
						&& !"zversion".equals(name)
						&& column!=null){
					if(z.isNotNull(value)) {
						//字段必须是表定义中包含的字段
						if(z.isNotNull(columnMap.get(name))) {
							sql.append(name+" , ");
						}
					}else if(z.isNotNull(column.getColumn_default_type())) {
						//添加默认值字段
						sql.append(name+" , ");
					}
				}
			}
			sql.append(" create_user,create_time,update_user,update_time,orgid,zversion,zid ) values ( ");
			//添加值
			for(z_form_table_column column:columnList) {
				String name = column.getColumn_id();//获取参数名
				String value = bean.get(column.getColumn_id());
				if(!"zid".equals(name)
						&& !"create_user".equals(name)
						&& !"update_user".equals(name)
						&& !"create_time".equals(name)
						&& !"update_time".equals(name)
						&& !"seq".equals(name)
						&& !"orgid".equals(name)
						&& !"zversion".equals(name)
						&& column!=null){

					String Column_type = column.getColumn_type();//获取字段类型

					if(z.isNotNull(value)) {
						if("2".equals(Column_type)) {//如果是数值，不用加单引号
							sql.append(value+",");
						}else {
							//内容特殊字符转意
							value = StringUtil.conversionSQL(value);
							sql.append("'"+value+"',");
						}
					}else if(z.isNotNull(column.getColumn_default_type())) {
						//添加默认值
						if("0".equals(column.getColumn_default_type())) {//固定值
							sql.append("'"+column.getColumn_default()+"',");
						}else if("1".equals(column.getColumn_default_type())) {//系统时间
							sql.append("'"+DateUtil.getDateTime()+"',");
						}else if("2".equals(column.getColumn_default_type())) {//系统日期
							sql.append("'"+DateUtil.getDate()+"',");
						}else if("3".equals(column.getColumn_default_type())) {//当前用户
							sql.append("'"+bean.get("session_userid")+"',");
						}else if("4".equals(column.getColumn_default_type())) {//当前组织
							sql.append("'"+bean.get("session_orgid")+"',");
						}else if("5".equals(column.getColumn_default_type())) {//随机数字编号
							sql.append("'"+z.newNumber()+"',");
						}else if("6".equals(column.getColumn_default_type())) {//随机数字字母编号
							sql.append("'"+z.newZid(table.getTable_id())+"',");
						}else if("7".equals(column.getColumn_default_type())) {//连续数字编号
							sql.append("'"+newContinuityNumber(table.getTable_id())+"',");
						}
					}

				}

			}
			sql.append("'"+bean.get("session_userid")+"',");//创建者

			if(z.isNotNull(bean.get("create_time"))){
				sql.append("'"+bean.get("create_time")+"',");//创建时间
			}else{
				sql.append("now(),");//创建时间
			}
			sql.append("'"+bean.get("session_userid")+"',");//修改者

			if(z.isNotNull(bean.get("update_time"))){
				sql.append("'"+bean.get("update_time")+"',");//修改时间
			}else{
				sql.append("now(),");//修改时间
			}

			sql.append("'"+bean.get("session_orgid")+"',");//所属组织
			sql.append("0,");//版本号
			sql.append("'"+bean.get("zid")+"' )");//zid
			return sql.toString();
		}else {
			return null;
		}

	}



	/**
	 * 创建修改SQL
	 * @param bean
	 * @return
	 */
	private String CreateUpdateForBeanSQL(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception {
		if(table!=null && columnList!=null && columnList.size()>0) {
			//创建SQL
			StringBuffer sql = new StringBuffer();
			sql.append("update "+table.getTable_id()+" set ");

			for (String key : bean.keySet()) {
				String name = key.trim();//获取参数名
				String value = bean.get(key);//根据参数名获取值
				z_form_table_column column = columnMap.get(name);

				if(column!=null
						&& !"zid".equals(name)
						&& !"create_user".equals(name)
						&& !"update_user".equals(name)
						&& !"create_time".equals(name)
						&& !"update_time".equals(name)
						&& !"seq".equals(name)
						&& !"pid".equals(name)) {

					String column_type = column.getColumn_type();

					//内容特殊字符转意
					value = StringUtil.conversionSQL(value);
					if(value!=null) {
						if("0".equals(column_type)) {//文本
							sql.append(name+" = '"+value+"',");
						}else if("1".equals(column_type)) {//多行文本
							sql.append(name+" = '"+value+"',");
						}else if("2".equals(column_type) && !"".equals(value)) {//数字
							sql.append(name+" = "+value+",");
						}else if("3".equals(column_type)) {//文件
							sql.append(name+" = '"+value+"',");
						}else if("4".equals(column_type)) {//图片
							sql.append(name+" = '"+value+"',");
						}else if("5".equals(column_type)) {//多选
							sql.append(name+" = '"+value+"',");
						}else if("6".equals(column_type)) {//单选
							sql.append(name+" = '"+value+"',");
						}else if("7".equals(column_type)) {//下拉框
							sql.append(name+" = '"+value+"',");
						}else if("8".equals(column_type)) {//Z5
							sql.append(name+" = '"+value+"',");
						}else if("9".equals(column_type)) {//日期
							if(z.isNull(value)) {
								sql.append(name+" = null,");
							}else {
								sql.append(name+" = '"+value+"',");
							}
						}else if("10".equals(column_type)) {//日期时间
							if(z.isNull(value)) {
								sql.append(name+" = null,");
							}else {
								sql.append(name+" = '"+value+"',");
							}
						}else if("11".equals(column_type)) {//HTML输入框
							sql.append(name+" = '"+value+"',");
						}else if("12".equals(column_type)) {//源码输入框
							sql.append(name+" = '"+value+"',");
						}
					}

				}
			}

			//更新修改人
			if(z.isNotNull(bean.get("session_userid"))) {
				sql.append(" update_user = '"+bean.get("session_userid")+"', ");
			}

			//判读是否加版本号
			if(z.isNotNull(bean.get("zversion"))) {
				sql.append(" zversion = zversion + 1, ");
				//更新修改时间
				sql.append(" update_time = now() ");
				sql.append(" WHERE zid = '"+bean.get("zid")+"' and zversion = "+bean.get("zversion")+" ");
			}else {
				//更新修改时间
				sql.append(" update_time = now() ");
				sql.append(" WHERE zid = '"+bean.get("zid")+"'  ");
			}

			return sql.toString();
		}else {
			return null;
		}
	}

	/**
	 * 创建修改SQL
	 * @param bean
	 * @return
	 */
	private String CreateUpdateSQL(HashMap<String,String> bean,z_form_table table,HashMap<String,z_form_table_column> columnMap,List<z_form_table_column> columnList) throws Exception {
		if(table!=null && columnList!=null && columnList.size()>0) {
			//创建SQL
			StringBuffer sql = new StringBuffer();
			sql.append("update "+table.getTable_id()+" set ");

			for(z_form_table_column column:columnList) {
				String name = column.getColumn_id();//获取参数名
				String value = bean.get(column.getColumn_id());

				if(column!=null
						&& !"zid".equals(name)
						&& !"create_user".equals(name)
						&& !"update_user".equals(name)
						&& !"create_time".equals(name)
						&& !"update_time".equals(name)
						&& !"seq".equals(name)
						&& !"pid".equals(name)) {

					String column_type = column.getColumn_type();

					//内容特殊字符转意
					value = StringUtil.conversionSQL(value);
					if(value!=null) {
						if("0".equals(column_type)) {//文本
							sql.append(name+" = '"+value+"',");
						}else if("1".equals(column_type)) {//多行文本
							sql.append(name+" = '"+value+"',");
						}else if("2".equals(column_type) && !"".equals(value)) {//数字
							sql.append(name+" = "+value+",");
						}else if("3".equals(column_type)) {//文件
							sql.append(name+" = '"+value+"',");
						}else if("4".equals(column_type)) {//图片
							sql.append(name+" = '"+value+"',");
						}else if("5".equals(column_type)) {//多选
							sql.append(name+" = '"+value+"',");
						}else if("6".equals(column_type)) {//单选
							sql.append(name+" = '"+value+"',");
						}else if("7".equals(column_type)) {//下拉框
							sql.append(name+" = '"+value+"',");
						}else if("8".equals(column_type)) {//Z5
							sql.append(name+" = '"+value+"',");
						}else if("9".equals(column_type)) {//日期
							if(z.isNull(value)) {
								sql.append(name+" = null,");
							}else {
								sql.append(name+" = '"+value+"',");
							}
						}else if("10".equals(column_type)) {//日期时间
							if(z.isNull(value)) {
								sql.append(name+" = null,");
							}else {
								sql.append(name+" = '"+value+"',");
							}
						}else if("11".equals(column_type)) {//HTML输入框
							sql.append(name+" = '"+value+"',");
						}else if("12".equals(column_type)) {//源码输入框
							sql.append(name+" = '"+value+"',");
						}
					}

				}
			}

			//更新修改人
			if(z.isNotNull(bean.get("session_userid"))) {
				sql.append(" update_user = '"+bean.get("session_userid")+"', ");
			}

			//判读是否加版本号
			if(z.isNotNull(bean.get("zversion"))) {
				sql.append(" zversion = zversion + 1, ");
				//更新修改时间
				sql.append(" update_time = now() ");
				if(z.isNotNull(bean.get("zids"))) {
					String zids = StringUtil.ListToSqlInArray(bean.get("zids"));
					sql.append(" WHERE zid in("+zids+") and zversion = "+bean.get("zversion")+" ");
				}else {
					sql.append(" WHERE zid = '"+bean.get("zid")+"' and zversion = "+bean.get("zversion")+" ");
				}

			}else {
				//更新修改时间
				sql.append(" update_time = now() ");
				if(z.isNotNull(bean.get("zids"))) {
					String zids = StringUtil.ListToSqlInArray(bean.get("zids"));
					sql.append(" WHERE zid in("+zids+") ");
				}else {
					sql.append(" WHERE zid = '"+bean.get("zid")+"'  ");
				}

			}

			return sql.toString();
		}else {
			return null;
		}
	}


	/**
	 * 根据查询条件json转成SQL条件
	 * @param query_terms
	 * @return
	 */
	protected String CreateQueryTerms(String query_terms) {
		StringBuffer sql_query_terms = new StringBuffer();
		List<QueryTerms> qlist = JsonUtil.jsonToList(query_terms, QueryTerms.class);
		if(qlist!=null && qlist.size()>0 && qlist.get(0) instanceof QueryTerms) {
			for (QueryTerms queryTerms : qlist) {
				//添加字段名 添加比较类型  搜索内容
				if(!"0".equals(queryTerms.getComparisonColumnId())  &&//字段名不为空
						!"0".equals(queryTerms.getComparisonType()) &&//比较符不为空
						!"".equals(queryTerms.getComparisonValue()) && queryTerms.getComparisonValue()!=null) {//搜索值不为空
					if("1".equals(queryTerms.getComparisonType())) {
						sql_query_terms.append(queryTerms.getComparisonColumnId()+" "+"="+" '"+queryTerms.getComparisonValue()+"'");
					}else if("2".equals(queryTerms.getComparisonType())){
						sql_query_terms.append(queryTerms.getComparisonColumnId()+" "+"like"+" '%"+queryTerms.getComparisonValue()+"%'");
					}else if("3".equals(queryTerms.getComparisonType())){
						sql_query_terms.append(queryTerms.getComparisonColumnId()+" "+">"+" '"+queryTerms.getComparisonValue()+"'");
					}else if("4".equals(queryTerms.getComparisonType())){
						sql_query_terms.append(queryTerms.getComparisonColumnId()+" "+">="+" '"+queryTerms.getComparisonValue()+"'");
					}else if("5".equals(queryTerms.getComparisonType())){
						sql_query_terms.append(queryTerms.getComparisonColumnId()+" "+"<"+" '"+queryTerms.getComparisonValue()+"'");
					}else if("6".equals(queryTerms.getComparisonType())){
						sql_query_terms.append(queryTerms.getComparisonColumnId()+" "+"<="+" '"+queryTerms.getComparisonValue()+"'");
					}else if("7".equals(queryTerms.getComparisonType())){
						sql_query_terms.append(queryTerms.getComparisonColumnId()+" "+"!="+" '"+queryTerms.getComparisonValue()+"'");
					}else {
						sql_query_terms.append(queryTerms.getComparisonColumnId()+" "+"like"+" '%"+queryTerms.getComparisonValue()+"%'");
					}

				}

				//添加条件连接
				if(!"0".equals(queryTerms.getConnectorType()) && queryTerms.getConnectorType()!=null) {
					if(queryTerms.getConnectorType().equals("1")) {
						sql_query_terms.append(" and ");
					}
					if(queryTerms.getConnectorType().equals("2")) {
						sql_query_terms.append(" or ");
					}
				}

			}
		}

		return sql_query_terms.toString();
	}

	/**
	 * 解析SQL获取表名和字段信息
	 * @param bean
	 * @return map.tableId = 表名    map.columnList = 字段类型
	 * @throws Exception
	 */
	protected Result AnalysisSQL(HashMap<String, String> bean, String sql) throws Exception {
		Result result = new Result();
		HashMap map = new HashMap();
		List<String[]> columnList = new ArrayList<String[]>();
		SqlSession ss = null;
		if(z.isNull(bean.get("dbid")) || "z".equals(bean.get("dbid"))) {
			ss = sqlSession;
		}else {
			ss = z.dbs.get(bean.get("dbid"));
		}
		Connection conn = ss.getConfiguration().getEnvironment().getDataSource().getConnection();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery(sql);
		ResultSetMetaData table = rs.getMetaData();
		List<String> tablenameList = new ArrayList<>();

		for (int i = 1; i <= table.getColumnCount(); i++) {

			z_db_table dbt = z.dbTableMap.get(bean.get("dbid")+"_"+table.getTableName(i));
			String [] array = new String[4];
			array[0] = table.getColumnName(i);//字段ID
			array[1] = table.getColumnLabel(i);//字段名
			if(z.isNotNull(dbt) && table.getColumnName(i).equals(dbt.getTable_pk())){
				array[2] = "1";//主键
			}else{
				array[2] = "0";//主键
			}
			array[3] = table.getTableName(i);//表名

			tablenameList.add(table.getTableName(i));//表名
			columnList.add(array);
		}

		//表名去重
		tablenameList = tablenameList.stream().distinct().collect(Collectors.toList());
		String tablenames = StringUtil.ListToString(tablenameList,",","","");

		map.put("tableId",tablenames);
		map.put("columnList",columnList);
		result.setSuccess(map);
		st.close();
		conn.close();
		return result;
	}

	/**
	 * 获取用户指定表单的常用查询条件
	 * @param bean
	 * @return
	 */
	protected String getQueryInfoList(HashMap<String, String> bean) {
		String tableId = bean.get("tableId");
		String userid = bean.get("session_userid");
		z_form_query qq = new z_form_query();
		qq.setTableid(tableId);
		qq.setUserid(userid);
		List<z_form_query> list = sqlSession.selectList("z_form_query_select", qq);
		if(list.size()>0) {
			return JsonUtil.listToJson(list);
		}else {
			return "";
		}
	}
	protected String getQueryInfoListR(z_report r,String userid) {
		z_report_query qq = new z_report_query();
		qq.setReportid(r.getReportid());
		qq.setUserid(userid);
		List<z_report_query> list = sqlSession.selectList("z_report_query_select", qq);
		if(list.size()>0) {
			return JsonUtil.listToJson(list);
		}else {
			return "";
		}
	}

	/**
	 * 创建默认值
	 * @param bean
	 * @return
	 */
	protected HashMap<String,String> CreateDefaultValue(HashMap<String, String> bean) throws Exception {
		//获取表名
		String table_name = String.valueOf(bean.get("tableId"));

		//根据表名获取表信息
		z_form_table table = z.tables.get(table_name);
		if(z.isNotNull(table)){

			//生成zid 如果number不为空，默认zid=number
			if(z.isNull(bean.get("zid"))) {
				if(z.isNotNull(bean.get("number"))){
					bean.put("zid",bean.get("number"));
				}else{
					bean.put("zid", z.newZid(table.getTable_id()));
				}
			}

			List<z_form_table_column> columnList = table.getZ_form_table_column_list();
			for(z_form_table_column column:columnList) {
				if(z.isNotNull(column.getColumn_default_type())) {
					//添加默认值
					if("0".equals(column.getColumn_default_type())) {//固定值
						bean.put(column.getColumn_id(),column.getColumn_default());
					}else if("1".equals(column.getColumn_default_type())) {//系统时间
						bean.put(column.getColumn_id(),DateUtil.getDateTime());
					}else if("2".equals(column.getColumn_default_type())) {//系统日期
						bean.put(column.getColumn_id(),DateUtil.getDate());
					}else if("3".equals(column.getColumn_default_type())) {//当前用户
						bean.put(column.getColumn_id(),bean.get("session_userid"));
					}else if("4".equals(column.getColumn_default_type())) {//当前组织
						bean.put(column.getColumn_id(),bean.get("session_orgid"));
					}else if("5".equals(column.getColumn_default_type())) {//随机数字编号
						bean.put(column.getColumn_id(),z.newNumber());
					}else if("6".equals(column.getColumn_default_type())) {//随机数字字母编号
						bean.put(column.getColumn_id(),z.newZid(table.getTable_id()));
					}else if("7".equals(column.getColumn_default_type())) {//连续数字编号
						bean.put(column.getColumn_id(),newContinuityNumber(table.getTable_id()));
					}
				}
			}
		}
		return bean;
	}


	protected Result r_update(HashMap<String, String> bean, HttpServletRequest request) throws Exception {
		Result result = new Result();
		z_report r = z.reports.get(bean.get("zid"));
		if(z.isNull(r)) {
			throw new Exception("未获取到报表信息，无法执行保存");
		}
		//根据List转成Map
		List<z_report_column> columnList = r.getZ_report_column_list();
		HashMap<String,z_report_column> columnMap = new HashMap<String, z_report_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_report_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}
		//插入前事件
		r_updateBefore(bean,columnMap,columnList);
		//创建执行SQL
		String sql = R_CreateUpdateSQL(bean,r,columnMap,columnList);
		int count = 0;
		if(z.isNotNull(r.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(r.getDbid());
			count = s.update("update",sql);
		}else {
			z.Exception("r_update: dbid is null");
		}

		if(count==0) {
			result.setCode(Code.ERROR);
			result.setMsg("r_update保存数据失败，该记录经已被修改，请刷新后重新修改保存。");
		}else {
			result.setCode(Code.SUCCESS);
			result.setMsg("保存成功");
			result.setData(bean);
		}
		return result;
	}

	protected Result r_insert(HashMap<String, String> bean, HttpServletRequest request) throws Exception {
		Result result = new Result();
		z_report r = z.reports.get(bean.get("zid"));
		if(z.isNull(r)) {
			throw new Exception("未获取到报表信息，无法执行保存");
		}
		//根据List转成Map
		List<z_report_column> columnList = r.getZ_report_column_list();
		HashMap<String,z_report_column> columnMap = new HashMap<String, z_report_column>();
		for (int i = 0; i < columnList.size(); i++) {
			z_report_column column = columnList.get(i);
			columnMap.put(column.getColumn_id(), column);
		}
		//插入前事件
		r_insertBefore(bean,columnMap,columnList);
		//创建执行SQL
		String sql = R_CreateInsertSQL(bean,r,columnMap,columnList);
		int count = 0;
		if(z.isNotNull(r.getDbid())) {
			SqlSessionTemplate s = z.dbs.get(r.getDbid());
			count = s.insert("insert",sql);
		}else {
			z.Exception("r_insert: dbid is null");
		}
		if(count!=1) {
			result.setCode(Code.ERROR);
			result.setMsg("r_insert异常，同时插入"+count+"条数据");
		}else {
			//设置返回
			result.setCode(Code.SUCCESS);
			result.setMsg("保存成功");
			result.setData(bean);
		}
		return result;
	}

	private void r_insertBefore(HashMap<String,String> bean,HashMap<String,z_report_column> columnMap,List<z_report_column> columnList) throws Exception {
		for(z_report_column column:columnList) {
			String name = column.getColumn_id();//获取参数名
			String value = bean.get(column.getColumn_id());
			if(column!=null){
				if(z.isNotNull(value)) {
					//字段必须是表定义中包含的字段
					if(z.isNotNull(columnMap.get(name))) {
						//验证有正则表达式的字段
						if(z.isNotNull(column.getRegex())){
							z_regex r = z.regexs.get(column.getRegex());
							if(z.isNotNull(r) && z.isNotNull(r.getRegex())){
								boolean v = StringUtil.vRegex(value,r.getRegex());
								if(!v){
									z.Exception("r_insert异常|["+column.getColumn_name()+"]数据值校验失败，不符合["+r.getName()+"]验证规则");
								}
							}
						}
					}
				}
			}
		}

	}


	/**
	 * 创建插入SQL
	 * @param bean
	 * @return
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws Exception
	 */
	private String R_CreateInsertSQL(HashMap<String,String> bean,z_report r,HashMap<String,z_report_column> columnMap,List<z_report_column> columnList) throws Exception{

		if(r!=null && columnList!=null && columnList.size()>0) {
			//创建SQL
			StringBuffer sql = new StringBuffer();
			z_db_table dbt = z.dbTableMap.get(r.getDbid()+"_"+r.getTableid());
			String table_pk = dbt.getTable_pk();
			String table_pk_value = bean.get(dbt.getTable_pk());

			sql.append("insert into "+r.getTableid()+" ( ");
			for (int i = 0; i < columnList.size(); i++) {
				z_report_column column = columnList.get(i);
				String name = column.getColumn_id();//获取参数名
				String value = bean.get(column.getColumn_id());
				if(!name.equals(table_pk)){
					if(z.isNotNull(value)) {
						//字段必须是表定义中包含的字段
						if(z.isNotNull(columnMap.get(name))) {
							sql.append(name+" , ");
						}
					}else if(z.isNotNull(column.getColumn_default_type())) {
						//添加默认值字段
						sql.append(name+" , ");
					}
				}
			}


			sql.append(table_pk);
			sql.append(")values(");
			//添加值
			for (int i = 0; i < columnList.size(); i++) {
				z_report_column column = columnList.get(i);
				String name = column.getColumn_id();//获取参数名
				String value = bean.get(column.getColumn_id());
				String Column_type = column.getColumn_type();//获取字段类型
				if(!name.equals(table_pk)){
					if(z.isNotNull(value)) {
						if("2".equals(Column_type)) {//如果是数值，不用加单引号
							sql.append(value+" , ");
						}else {
							//内容特殊字符转意
							value = StringUtil.conversionSQL(value);
							sql.append("'"+value+"',");
						}
					}else if(z.isNotNull(column.getColumn_default_type())) {
						//添加默认值
						if("0".equals(column.getColumn_default_type())) {//固定值
							sql.append("'"+column.getColumn_default()+"',");
						}else if("1".equals(column.getColumn_default_type())) {//系统时间
							sql.append("'"+DateUtil.getDateTime()+"',");
						}else if("2".equals(column.getColumn_default_type())) {//系统日期
							sql.append("'"+DateUtil.getDate()+"',");
						}else if("3".equals(column.getColumn_default_type())) {//当前用户
							sql.append("'"+bean.get("session_userid")+"',");
						}else if("4".equals(column.getColumn_default_type())) {//当前组织
							sql.append("'"+bean.get("session_orgid")+"',");
						}else if("5".equals(column.getColumn_default_type())) {//随机数字编号
							sql.append("'"+z.newNumber()+"',");
						}else if("6".equals(column.getColumn_default_type())) {//随机数字字母编号
							sql.append("'"+z.newZid(r.getTableid())+"',");
						}else if("7".equals(column.getColumn_default_type())) {//连续数字编号
							sql.append("'"+newContinuityNumber(r.getTableid())+"',");
						}
					}
				}
			}
			sql.append(table_pk_value);
			sql.append(")");
			return sql.toString();
		}else {
			return null;
		}

	}


	private void r_updateBefore(HashMap<String,String> bean,HashMap<String,z_report_column> columnMap,List<z_report_column> columnList) throws Exception {
		for(z_report_column column:columnList) {
			String name = column.getColumn_id();//获取参数名
			String value = bean.get(column.getColumn_id());
			if(column!=null){
				if(z.isNotNull(value)) {
					//字段必须是表定义中包含的字段
					if(z.isNotNull(columnMap.get(name))) {
						//验证有正则表达式的字段
						if(z.isNotNull(column.getRegex())){
							z_regex r = z.regexs.get(column.getRegex());
							if(z.isNotNull(r) && z.isNotNull(r.getRegex())){
								boolean v = StringUtil.vRegex(value,r.getRegex());
								if(!v){
									z.Exception("r_insert异常|["+column.getColumn_name()+"]数据值校验失败，不符合["+r.getName()+"]验证规则");
								}
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 创建修改SQL
	 * @param bean
	 * @return
	 */
	private String R_CreateUpdateSQL(HashMap<String,String> bean,z_report r,HashMap<String,z_report_column> columnMap,List<z_report_column> columnList) throws Exception {
		if(r!=null && columnList!=null && columnList.size()>0) {
			//创建SQL
			StringBuffer sql = new StringBuffer();
			sql.append("update "+r.getTableid()+" set ");

			for (int i = 0; i < columnList.size(); i++) {
				z_report_column column = columnList.get(i);
				String name = column.getColumn_id();//获取参数名
				String value = bean.get(column.getColumn_id());
				if(column!=null) {
					String column_type = column.getColumn_type();

					//内容特殊字符转意
					value = StringUtil.conversionSQL(value);
					if(z.isNull(value)){
						sql.append(name+" = null");
					}else{
						if("0".equals(column_type)) {//文本
							sql.append(name+" = '"+value+"'");
						}else if("1".equals(column_type)) {//多行文本
							sql.append(name+" = '"+value+"'");
						}else if("2".equals(column_type) && !"".equals(value)) {//数字
							sql.append(name+" = "+value+"");
						}else if("3".equals(column_type)) {//文件
							sql.append(name+" = '"+value+"'");
						}else if("4".equals(column_type)) {//图片
							sql.append(name+" = '"+value+"'");
						}else if("5".equals(column_type)) {//多选
							sql.append(name+" = '"+value+"'");
						}else if("6".equals(column_type)) {//单选
							sql.append(name+" = '"+value+"'");
						}else if("7".equals(column_type)) {//下拉框
							sql.append(name+" = '"+value+"'");
						}else if("8".equals(column_type)) {//Z5
							sql.append(name+" = '"+value+"'");
						}else if("9".equals(column_type)) {//日期
							if(z.isNull(value)) {
								sql.append(name+" = null");
							}else {
								sql.append(name+" = '"+value+"'");
							}
						}else if("10".equals(column_type)) {//日期时间
							if(z.isNull(value)) {
								sql.append(name+" = null");
							}else {
								sql.append(name+" = '"+value+"'");
							}
						}else if("11".equals(column_type)) {//HTML输入框
							sql.append(name+" = '"+value+"'");
						}else if("12".equals(column_type)) {//源码输入框
							sql.append(name+" = '"+value+"'");
						}
					}
				}

				if(columnList.size() != i+1){
					sql.append(" , ");
				}
			}

			//where
			sql.append(" where 1=1 ");
			for (int i = 0; i < columnList.size(); i++) {
				z_report_column column = columnList.get(i);
				if(z.isNotNull(column) && "1".equals(column.getIs_pk())) {
					String name = column.getColumn_id();//获取参数名
					String value = bean.get(column.getColumn_id());
					sql.append(" and "+name+" = "+"'"+value+"'");
				}
			}

			return sql.toString();
		}else {
			return null;
		}
	}

	protected Result r_delete(HashMap<String, String> bean, HttpServletRequest request) throws Exception{
		String reportzid = bean.get("zid");
		String table_name = String.valueOf(bean.get("tableId"));
		String ReportTablePkId = bean.get("ReportTablePkId");
		String zids = bean.get("zids");
		z_report r = z.reports.get(reportzid);
		if(r==null) {
			throw new Exception("报表无效，无法执行删除操作");
		}
		//执行删除任务
		Result result = new Result();
		SqlSessionTemplate s = null;
		if(z.isNotNull(r.getDbid())) {
			s = z.dbs.get(r.getDbid());
		}else {
			z.Exception("delete: dbid is null");
		}

		if(!"".equals(zids) && zids!=null) {
			String [] zids_array = zids.split(",");
			int romcount = 0;
			for (int i = 0; i < zids_array.length; i++) {
				//删除
				String sql = "delete from "+table_name + " where "+ReportTablePkId+" = '"+zids_array[i]+"'";
				int deletecounts = s.delete("delete", sql);
				//如果删除成功，累计删除条数
				if(deletecounts>0) {
					romcount = romcount + deletecounts;
				}
			}
			if(romcount>0) {
				result.setCode(Code.SUCCESS);
				result.setMsg("ok");
				result.setData(romcount);
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("删除0条记录");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("zids is null");
		}
		return result;
	}
}